package cn.itcast.io.c;

import java.io.*;
import java.nio.charset.Charset;

public class CharStreamDemo {

    // 需求：读取一个文本文件，判断里面有多少个 好 字
    public static void main(String[] args) throws IOException {
        
        // 1. 创建一个文本
        createText();
        //读取一个文本文件内容，并输出
        printContent();
        
        // 2. 读取字节流
        System.out.println("---读取字节---");
        getByteStream();
        
        // 3. 读取字符流
        System.out.println("---读取字符---");
        getCharStream();
    }

    private static void printContent() throws IOException{
        //File file = new File("C:\\Users\\hz21076971\\Desktop\\myJava\\cn.txt");
        File file = new File("tempFile\\cn.txt");
        FileInputStream fis = new FileInputStream(file);
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = fis.read(buffer)) != -1){
            String str = new String(buffer, 0, len);
            System.out.println(str);
        }
    }

    private static void getCharStream() throws IOException{
        //File file = new File("C:\\Users\\hz21076971\\Desktop\\myJava\\cn.txt");
        File file = new File("tempFile\\cn.txt");
        FileReader fileReader = new FileReader(file);
        int ch1 = fileReader.read();
        System.out.println("读取一个字符："+ch1);
        int ch2 = fileReader.read();
        System.out.println("读取一个字符："+ch2);
        System.out.println((char)20320);
    }

    private static void getByteStream() throws IOException{
        //File file = new File("C:\\Users\\hz21076971\\Desktop\\myJava\\cn.txt");
        File file = new File("tempFile\\cn.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        int ch1 = fileInputStream.read();
        System.out.println("读取一个字节："+ch1);
        
        int ch2 = fileInputStream.read();
        System.out.println("读取一个字节："+ch2);
    }

    private static void createText() throws IOException {
        File file = new File("tempFile\\cn.txt");
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write("a你好你好".getBytes(Charset.forName("GBK")));
        fileOutputStream.close();
    }
}
